<?php
class SP_Form_Simple
{
	private $fields=array();
	public $attributes=array();
	public $name;
	public $method='post';
	public $action='';
	private $data;
	
	public function __construct($attr=null)
	{
		if(is_array($attr))
		{
			foreach($attr as $key => $value)
			{
				$this->$key=$value;
			}
		}
	}
	
	public function setField($field)
	{
		if( $this->hasField($name) ) throw new exception('Field with name "'.$name.'" already exist');
		$field->form_name=$this->name;
		$this->fields[$field->name]=$field;
		return $this;
	}
	
	public function setFields($fields)
	{
		foreach($fields as $field)
		{
			$this->setField($field);
		}
	}
	
	public function hasField($name)
	{
		return isset($this->fields[$name]);
	}
	
	public function getField($name)
	{
		if( !$this->hasField($name) ) throw new exception('Form class "'.$this->name.'" has not "'.$name.'" field');
		return $this->fields[$name];
	}
	
	public function getHtml()
	{
		$options=SP_Helpers_Html::makeOptions($this->attributes);
		$out='<form action="'.$this->action.'" method="'.$this->method.'"'.$options.'><table>';
		foreach($this->fields as $field)
		{
			$out.='<tr><td>'.$field->getHtml().$field->getLabel().'</td><td>'.$field->getError().'</td></tr>';
		}
		$out.='</table></form>';
		return $out;
	}
	
	public function checkData()
	{
		if (!SP_Helper_Post::has($this->name) ) return false;
		$this->data=SP_Helper_Post::get($this->name);
		$result=true;
		foreach($this->fields as $field)
		{
			$result = $result * $field->setValue($this->data[$field->name]);
		}
		return $result;
	}
	
	public function get($name)
	{
		return $this->data[$name];
	}
	
	public function set($name, $value)
	{
		$field=$this->getField($name);
		$field->setValue($value);
	}
	
	public function setArray($array)
	{
		foreach($array as $name => $value)
		{
			$this->set($name, $value);
		}
	}
	
}